package org.anderground.app.view.dialogs;

import java.util.List;

import org.anderground.app.R;

import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @param <T>
 */
public class ItemsDialog<T> extends BaseDialog implements
		AdapterView.OnItemClickListener, DialogInterface.OnClickListener {

	/** the subscriber that would be notified about most of events */
	protected Listener listener;

	/** View to attach to the dialog */
	private ListView itemsView;

	/** a list of filenames */
	protected T[] items;

	/**
	 * public constructor
	 * 
	 * @param context
	 */
	public ItemsDialog(Context context) {
		super(context);

		this.itemsView = new ListView(context);
		this.itemsView.setOnItemClickListener(this);

		setView(itemsView);
		setNegativeButton(R.string.cancel, this);

	}

	/**
	 * show the dialog if it has not already shown
	 * 
	 * @param items
	 */
	public void show(List<T> items) {
		this.show(items, new ArrayAdapter<T>(getContext(), R.layout.file_row,
				items));
	}

	/**
	 * show the dialog if it has not already shown
	 * 
	 * @param items
	 */
	public void show(T[] items) {
		this.show(items, new ArrayAdapter<T>(getContext(), R.layout.file_row,
				items));
	}

	/**
	 * show the dialog using custom ArrayAdapter
	 * 
	 * @param items
	 * @param arrayAdapter
	 */
	@SuppressWarnings("unchecked")
	protected void show(List<T> items, ArrayAdapter<T> arrayAdapter) {
		this.show((T[]) items.toArray(), arrayAdapter);
	}

	/**
	 * show the dialog using custom ArrayAdapter
	 * 
	 * @param items
	 * @param arrayAdapter
	 */
	protected void show(T[] items, ArrayAdapter<T> arrayAdapter) {
		this.items = items;
		this.itemsView.setAdapter(arrayAdapter);

		show();
	}

	/**
	 * handles button clicks
	 * 
	 * @param dialog
	 * @param button
	 */
	public void onClick(DialogInterface dialog, int button) {
	}

	/**
	 * user selected an item from the list
	 * 
	 * @param parent
	 * @param v
	 * @param position
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	public void onItemClick(AdapterView parent, View v, int position, long id) {
		if (parent == this.itemsView) {
			if (listener != null) {
				listener.onItemSelected(this, items[position]);
			}
			hide();
		}
	}

	/**
	 * subscribe to notifications
	 * 
	 * @param listener
	 *            the listener
	 */
	public void setListener(Listener listener) {
		if (listener != null) {
			this.listener = listener;
		}
	}

	/**
	 * Listener interface.
	 * 
	 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
	 */
	public interface Listener {

		@SuppressWarnings("unchecked")
		public void onItemSelected(ItemsDialog itemsDialog, Object itemName);

	}

}
